#!/bin/bash
#@author dali
#统一启动3个jar包文件
#这里定义你的jar包名称
APP_NAME1=computer8080.jar
APP_NAME2=computer8081.jar
APP_NAME3=computer8082.jar

#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
    exit 1
}

#检查8080是否在运行
is_exist1(){
  pid1=`ps -ef|grep $APP_NAME1|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid1}" ]; then
   return 1
  else
    return 0
  fi
}

#检查8081是否在运行
is_exist2(){
  pid2=`ps -ef|grep $APP_NAME2|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid2}" ]; then
   return 1
  else
    return 0
  fi
}

#检查8082是否在运行
is_exist3(){
  pid3=`ps -ef|grep $APP_NAME3|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid3}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist1
  if [ $? -eq "0" ]; then
    echo "${APP_NAME1} is already running. pid=${pid1} ."
  else
    nohup java -jar $APP_NAME1 > /dev/null 2>&1 &
  fi

  is_exist2
  if [ $? -eq "0" ]; then
    echo "${APP_NAME2} is already running. pid=${pid2} ."
  else
    nohup java -jar $APP_NAME2 > /dev/null 2>&1 &
  fi

  is_exist3
  if [ $? -eq "0" ]; then
    echo "${APP_NAME3} is already running. pid=${pid3} ."
  else
    nohup java -jar $APP_NAME3 > /dev/null 2>&1 &
  fi
}

#停止方法
stop(){
  is_exist1
  if [ $? -eq "0" ]; then
    kill -9 $pid1
  else
    echo "${APP_NAME1} is not running"
  fi

  is_exist2
  if [ $? -eq "0" ]; then
    kill -9 $pid2
  else
    echo "${APP_NAME2} is not running"
  fi

  is_exist3
  if [ $? -eq "0" ]; then
    kill -9 $pid3
  else
    echo "${APP_NAME3} is not running"
  fi
}

#输出运行状态
status(){
  is_exist1
  if [ $? -eq "0" ]; then
    echo "${APP_NAME1} is running. Pid is ${pid1}"
  else
    echo "${APP_NAME1} is NOT running."
  fi

  is_exist2
  if [ $? -eq "0" ]; then
    echo "${APP_NAME2} is running. Pid is ${pid2}"
  else
    echo "${APP_NAME2} is NOT running."
  fi

  is_exist3
  if [ $? -eq "0" ]; then
    echo "${APP_NAME3} is running. Pid is ${pid3}"
  else
    echo "${APP_NAME3} is NOT running."
  fi
}

#重启
restart(){
  stop
  start
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac
